package com.study.springbootsecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.springbootsecurity.entity.Role;
import com.study.springbootsecurity.entity.business.Permission;
import com.study.springbootsecurity.exception.BusinessException;
import com.study.springbootsecurity.exception.ExceptionConstant;
import com.study.springbootsecurity.mapper.RoleMapper;
import com.study.springbootsecurity.mapper.SysMenuMapper;
import com.study.springbootsecurity.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: TODO 角色业务接口实现类
 * @author: Huangjianyun
 * @date: 2025-06-05 17:05
 */
@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private  RoleMapper roleMapper;
    private SysMenuMapper sysMenuMapper;
    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }
    @Autowired
    public void setSysMenuMapper(SysMenuMapper sysMenuMapper) {
        this.sysMenuMapper = sysMenuMapper;
    }

    @Override
    public List<Role> findByUserId(Long userId) {

        if (ObjectUtils.isEmpty(userId)) {
            throw new BusinessException("RoleServiceImpl实现类findByUserId方法的用户id参数不能为null~~~~~~~~~~");
        }
        List<Role> roles = roleMapper.findRolesByUserId(userId);
        List<Long> roleIds = roles.stream().map(Role::getId).toList();
        // 批量查询角色的权限
        List<Permission> permisList = sysMenuMapper.findPermissionByRoleIds(roleIds);
        // 权限roleId作为key分组 value为权限列表
        Map<Long, List<String>> permisMap = permisList.stream().collect(Collectors.groupingBy(Permission::getRoleId, Collectors.mapping(Permission::getPerms, Collectors.toList())));
        // 角色设置对应权限列表
        for (Role role : roles) {
            role.setPermissions(permisMap.getOrDefault(role.getId(),new ArrayList<>()));
        }
        return roles;
    }
}
